package com.qyhl.school.school.vlog.theme.detail;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.SingleChoiceDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogThemeDetailBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.TranslucentScrollView;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_VLOG_THEME_DETAIL)
public class SchoolVlogThemeDetailActivity extends BaseActivity
        implements SchoolVlogThemeDetailContract.SchoolVlogThemeDetailView, TranslucentScrollView.OnScrollChangedListener {
    @BindView(R2.id.cover)
    ImageView cover;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R2.id.scroll_view)
    TranslucentScrollView scrollView;
    @BindView(R2.id.toolbar_layout)
    RelativeLayout toolbarLayout;


    private float headerHeight;//顶部高度
    private float minHeaderHeight;//顶部最低高度，即Bar的高度

    private SchoolVlogThemeDetailPresenter mPresenter;

    private int lastId = 0;
    private int lastBoost = 0;

    private CommonAdapter<SchoolVlogBean> commonAdapter;

    private List<SchoolVlogBean> mDataList = new ArrayList<>();

    private int tagId;

    private String mVideoCoverPath;

    private String mVideoPath;

    /**
     * 视频选择
     */
    public static final int CHOOSE_VIDEO = 100;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_vlog_theme_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarDarkFont(false)
                .titleBar(toolbar)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }


    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new SchoolVlogThemeDetailPresenter(this);
        scrollView.setOnScrollChangedListener(this);
        tagId = getIntent().getIntExtra("tagId", 0);

        setSupportActionBar(toolbar);
        initMeasure();

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.setAdapter(commonAdapter = new CommonAdapter<SchoolVlogBean>(this, R.layout.item_school_vlog_home, mDataList) {
            @Override
            protected void convert(ViewHolder holder, SchoolVlogBean schoolVlogBean, int position) {
                holder.setText(R.id.nickName, schoolVlogBean.getAuthor().getNickName());
                holder.setText(R.id.tagName, "#" + schoolVlogBean.getTag().getName() + "#");
                holder.setText(R.id.description, schoolVlogBean.getInfo());

                RoundedImageView cover = holder.getView(R.id.cover);
                RoundedImageView headCover = holder.getView(R.id.head_cover);

                Glide.with(SchoolVlogThemeDetailActivity.this)
                        .load(schoolVlogBean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                Glide.with(SchoolVlogThemeDetailActivity.this)
                        .load(schoolVlogBean.getAuthor().getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headCover);
            }
        });

        mPresenter.getDetail(tagId, lastBoost, lastId);

    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = 0;
                lastBoost = 0;
                mPresenter.getDetail(tagId, lastBoost, lastId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastId = 0;
                lastBoost = 0;
                mPresenter.getDetail(tagId, lastBoost, lastId);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDetail(tagId, lastBoost, lastId);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) mDataList);
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_VLOG_PLAY)
                        .withBundle("list", bundle)
                        .withInt("position", position)
                        .withInt("tagId", tagId)
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(SchoolVlogThemeDetailBean bean, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();

            title.setText("#" + bean.getName() + "#");
            toolbarTitle.setText(bean.getName());
            summary.setText(bean.getInfo());

            Glide.with(this)
                    .load(bean.getImgUrl())
                    .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                    .into(cover);
        }
        List<SchoolVlogBean> beanList = bean.getVlogList();
        if (bean.getVlogList() != null && bean.getVlogList().size() > 0) {
            lastId = beanList.get(beanList.size() - 1).getId();
            lastBoost = beanList.get(beanList.size() - 1).getBoost();
            mDataList.addAll(beanList);
            commonAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                showToast("暂无更多主题！");
            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    private void initMeasure() {
        headerHeight = StringUtils.dip2px(this, 210);
        minHeaderHeight = StringUtils.dip2px(this, 68);
    }


    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
        //Y轴偏移量
        float scrollY = who.getScrollY();
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);
        //Toolbar背景色透明度
        toolbarLayout.setAlpha(offset);
    }


    @OnClick({R2.id.back_btn, R2.id.back, R2.id.shoot_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn || id == R.id.back) {
            finish();
        } else if (id == R.id.shoot_btn) {
            new SingleChoiceDialog.Builder(SchoolVlogThemeDetailActivity.this).setTitle("提示", R.color.global_black_lv2)
                    .addList(new String[]{"拍摄", "本地视频"})
                    .setCancelTextColor(R.color.global_base)
                    .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                        @Override
                        public void OnItemClick(String title, int position) {
                            switch (position) {
                                case 0:
                                    XXPermissions.with(SchoolVlogThemeDetailActivity.this)
                                            .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA, Permission.RECORD_AUDIO)
                                            .request(new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    if (all) {
                                                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                                            @Override
                                                            public void login(boolean isLogin) {
                                                                if (isLogin) {
                                                                    if (StringUtils.isMi8()) {
                                                                        ARouter.getInstance()
                                                                                .build(ARouterPathConstant.SCHOOL_SHOOT2)
                                                                                .withString("cover", mVideoCoverPath)
                                                                                .withString("video", mVideoPath)
                                                                                .withInt("tagId", tagId)
                                                                                .navigation();
                                                                    } else {
                                                                        ARouter.getInstance()
                                                                                .build(ARouterPathConstant.SCHOOL_SHOOT)
                                                                                .withString("cover", mVideoCoverPath)
                                                                                .withString("video", mVideoPath)
                                                                                .withInt("tagId", tagId)
                                                                                .navigation();
                                                                    }
                                                                } else {
                                                                    showToast("尚未登录或登录已失效！");
                                                                    RouterManager.routerLogin(SchoolVlogThemeDetailActivity.this, 0);
                                                                }
                                                            }

                                                            @Override
                                                            public void error(String s) {

                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                    break;
                                case 1:
                                    XXPermissions.with(SchoolVlogThemeDetailActivity.this)
                                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
                                            .request(new OnPermissionCallback() {
                                                @Override
                                                public void onGranted(List<String> permissions, boolean all) {
                                                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                                        @Override
                                                        public void login(boolean isLogin) {
                                                            if (isLogin) {
                                                                chooseVideo();
                                                            } else {
                                                                showToast("尚未登录或登录已失效！");
                                                                RouterManager.routerLogin(SchoolVlogThemeDetailActivity.this, 0);
                                                            }
                                                        }

                                                        @Override
                                                        public void error(String s) {

                                                        }
                                                    });
                                                }
                                            });
                                    break;
                                default:
                                    break;
                            }
                        }
                    })
                    .show();
        }
    }

    /**
     * 选择视频
     */
    private void chooseVideo() {
        PictureSelector.create(SchoolVlogThemeDetailActivity.this)
                .openGallery(PictureMimeType.ofVideo())
                .imageSpanCount(4)
                .previewVideo(true)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(false)
                .isZoomAnim(true)
                .compress(true)
                .videoMaxSecond(180)
                .videoMinSecond(2)
                .videoQuality(1)
                .recordVideoSecond(15)
                .forResult(CHOOSE_VIDEO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_VIDEO: {
                //视频选择
                List<LocalMedia> pic = PictureSelector.obtainMultipleResult(data);
                if (pic != null && pic.size() > 0) {
                    //视频路径
                    String path = pic.get(0).getPath();
                    getPicture(path);
                    mVideoPath = path;

                    ARouter.getInstance()
                            .build(ARouterPathConstant.SCHOOL_VLOG_UPLOAD)
                            .withInt("tagId",tagId)
                            .withString("cover",mVideoCoverPath)
                            .withString("video",mVideoPath)
                            .navigation();
                }
            }
            break;
            default:
                break;
        }
    }

    /**
     * 获取视频封面图
     */
    public void getPicture(String path) {
        File file = new File(path);
        //判断对象是否存在，不存在的话给出Toast提示
        if (file.exists()) {
            //提供统一的接口用于从一个输入媒体中取得帧和元数据
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(path);
            Bitmap bitmap = retriever.getFrameAtTime();
            String dirpath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic;
            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString() + ".png";
            mVideoCoverPath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic + File.separator + name;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mVideoCoverPath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("生成封面图失败");
            }
        } else {
            showToast("视频路径不存在");
        }
    }
}
